/**
 * Created by zxx on 2017-4-20.
 */
/**
 * 自定义组件容器
 * 属性：
 *   - multi 默认为false, 是否允许添加多个组件.
 *   - load 是否加载显示组件, 主要用于选项卡隐藏页加载.
 *   - margin 5, 组件上下间距, 默认为5
 */
function Custom(){};

Custom.inherit(Container);

/**
 * 初始化方法
 */
Custom.prototype.init = function () {
    Custom.base.init.call(this);
}

Custom.prototype.initLoad = function() {
    if (!$().sortable) {
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery-ui.min.js");
    }
    this._load = true;
    if (this.getAttribute().load &&
        this.getAttribute().load == "false") {
        this._load = false;
        this._hasLoad = false;
        this._loadData = null;
    }
    //容器组件
    this._widgets = [];
    //等待加载组件
    this._waitLoad = [];

    this._margin = 5;
    if (this.getAttribute().margin) {
        this._margin = parseInt(this.getAttribute().margin);
    }
    this._multi = false;
    if (this.getAttribute().multi
        && this.getAttribute().multi == "true") {
        this._multi = true;
    }
    $(this.getHTML()).sortable({
        cursor:'move',
        axis: 'y',
        tolerance:"pointer",
        scroll:true,
        items:'.custom-comp',
        zIndex:100001
    });
    var that = this;
    $(this.getHTML()).bind("sortstop", function(event, ui){
        var sortIDs = $(this).sortable('toArray');
        for (var i = 0 ; i < sortIDs.length ; i++) {
            var oComp = that.getWidget(sortIDs[i]);
            oComp.getLayoutData().num = i + 1;
        }
    });
    this._edit = false;
    this._develop = false; //开发者模式
}

/**
 * 更改为设计状态
 * @param isDevelop 是否开发模式，如果为true, 则显示设置和调试按钮.
 */
Custom.prototype.designer = function(isDevelop) {
    if (isDevelop) {
        this._develop = true;
    }
    this.addDesignStyle();
    $(this.getHTML()).sortable('enable');
    $(this.getHTML()).disableSelection();
    this._edit = true;
}

/**
 * 更改为展示状态
 */
Custom.prototype.viewer = function() {
    this.removeDesignStyle();
    $(this.getHTML()).enableSelection();
    $(this.getHTML()).sortable('disable');
    this._edit = false;
}


/**
 * 初始化样式
 * @param isDevelop 是否开发模式，如果为true, 则显示设置和调试按钮.
 */
Custom.prototype.addDesignStyle = function() {
    $(this.getHTML()).addClass("custom-design");
    var that = this;
    if (!this._addBtn) {
        this._addBtn = $(
            "<div class='custom-addbtn' title='添加组件'>" +
                "<span class='custom-addbtn-icon'>添加窗口部件</span>" +
            "</div>"
        );
        $(this.getHTML()).append(this._addBtn);
        var that = this;
        this._addBtn.click(function(){
            that.getComponent().postMessage({
                id:"MSG_CUSTOM_ADDWIDGET",
                control:that
            });
        });
    }
    this.judgeAddButton();
    for (var i = 0 ; i < this._widgets.length ; i++) {
        this.addWidgetMask(this._widgets[i]);
    }
}

Custom.prototype.addWidgetMask = function(comp) {
    $(comp.getHTML()).addClass("custom-comp");
    $(comp.getHTML()).append(
        "<div class='custom-comp-mask'>" +
            "<div class='custom-comp-text'></div>" +
            "<div class='custom-comp-handler'>" +
                "<div class='custom-comp-icon custom-comp-setting' title='设置'></div>" +
                "<div class='custom-comp-icon custom-comp-debug' title='调试'></div>" +
                "<div class='custom-comp-icon custom-comp-remove' title='删除'></div>" +
            "</div>" +
        "</div>"
    );
    if (!this._develop) {
        $(".custom-comp-setting", comp.getHTML()).hide();
        $(".custom-comp-debug", comp.getHTML()).hide();
    }
    var that = this;
    $(".custom-comp-setting", comp.getHTML()).click(function(){
        that.settingWidget(comp.getID());
    });
    $(".custom-comp-debug", comp.getHTML()).click(function(){
        that.debugWidget(comp.getID());
    });
    $(".custom-comp-remove", comp.getHTML()).click(function(){
        if (!confirm("是否确定删除?")) return;
        that.removeWidget(comp.getID());
    });
    $(".custom-comp-mask", comp.getHTML()).mouseover(function(){
        $(".custom-comp-text", this).text("标识: " + comp.getID());
        that.mouseoverWidget(comp.getID());
    });
    $(".custom-comp-mask", comp.getHTML()).mouseout(function(){
        $(".custom-comp-text", this).text("");
        that.mouseoutWidget(comp.getID());
    });
}


/**
 * 初始化样式
 */
Custom.prototype.removeDesignStyle = function() {
    $(this.getHTML()).removeClass("custom-design");
    if (this._addBtn) this._addBtn.hide();
    for (var i = 0 ; i < this._widgets.length ; i++) {
        var comp = this._widgets[i];
        $(comp.getHTML()).removeClass("custom-comp");
        $(".custom-comp-mask", comp.getHTML()).remove();
    }
}

/**
 * 添加组件
 * oData - {
 *     id:"",  //部件id
 *     cmpid:"", //显示部件类型id
 *     name:"",
 *     url:"",
 *     num:"",
 *     param:"", //部件参数
 *     chandler:"", //部件输出接口排除部件
 * }
 */
Custom.prototype.addWidget = function(oData) {
    if (!oData.num) {
        oData.num = this.getWidgetsLength() + 1;
    }
    var status = this.checkWidget(oData.id);
    if (!status) return;
    var oComponent = this.addItem("Component", {
        src:oData.url,
        id:oData.id,
        load:"false"
    });
    //设置参数和接口
    if (oData.param) oComponent.setParam(oData.param);
    if (oData.chandler) oComponent.setExCHandler(oData.chandler);
    //var loading = this.createLoad(oData.name);
    //loading.css("height", "200px");
    //$(oComponent.getHTML()).append(loading);
    oComponent.setLayoutData(oData);
    if (oData.num != 1) {
        $(oComponent.getHTML()).css("marginTop", this._margin + "px");
    }
    this._widgets.push(oComponent);
    this._waitLoad.push(oComponent);
    if (this._edit) {
        this.addWidgetMask(oComponent);
        this.judgeAddButton();
    }
}

Custom.prototype.checkWidget = function(cmpid) {
    for (var i = 0 ; i < this._widgets.length ; i++) {
        var oWidget = this._widgets[i];
        if (oWidget.getLayoutData().cmpid == cmpid) {
            if (!confirm("界面已存在该内容?是否继续添加?")) {
                return false;
            }
        }
    }
    return true;
}

/**
 * 根据是否多个组件设置按钮状态
 */
Custom.prototype.judgeAddButton = function() {
    if (!this._multi && this.getWidgetsLength() != 0) {
        this._addBtn.hide();
    } else {
        this._addBtn.show();
        $(this.getHTML()).append(this._addBtn);
    }
}

/**
 * 添加多个组件
 * @param oData
 */
Custom.prototype.addWidgets = function(oDatas) {
    //根据序号排序
    oDatas.sort(function(data1, data2){
        return parseInt(data1.num) - parseInt(data2.num);
    });
    if (this._load) {
        this.loadWidgets(oDatas);
    } else {
        this._loadData = oDatas;
    }
}

Custom.prototype.loadWidgets = function(oDatas) {
    for (var i = 0 ; i < oDatas.length ; i++) {
        this.addWidget(oDatas[i]);
    }
    this.startLoadWidget();
    this._hasLoad = true;
}

/**
 * 加载内容
 */
Custom.prototype.load = function() {
    if (this._loadData) {
        this.loadWidgets(this._loadData);
        this._loadData = null;
    }
}

/**
 * 重加载组件
 */
Custom.prototype.reload = function() {
    var widgets = this.getWidgets();
    var datas = [];
    for (var i = 0 ; i < widgets.length ; i++) {
        datas.push(widgets[i].getLayoutData());
    }
    this.removeAllElement();
    this._widgets = [];
    this.loadWidgets(datas);
}

/**
 * 删除组件
 */
Custom.prototype.removeAllWidget = function() {
    for (var i = 0 ; i < this._widgets.length ; i++) {
        this.delItem(this._widgets[i]);
    }
}

/**
 * 删除组件
 */
Custom.prototype.removeWidget = function(id) {
    var comp = this.getWidget(id);
    this.delItem(comp);
    this._widgets.splice(this.getWidgetIndex(id), 1);
    this.judgeAddButton();
}

/**
 * 调试组件
 */
Custom.prototype.debugWidget = function(id) {
    var oWidget = this.getWidget(id);
    this.getComponent().postMessage({
        id:"MSG_CUSTOM_DEBUGWIDGET",
        widget:oWidget
    });
}

/**
 * 设置组件
 */
Custom.prototype.settingWidget = function(id) {
    var oWidget = this.getWidget(id);
    this.getComponent().postMessage({
        id:"MSG_CUSTOM_SETTINGWIDGET",
        widget:oWidget
    });
}

/**
 * 鼠标移入部件
 */
Custom.prototype.mouseoverWidget = function(id) {
    var oWidget = this.getWidget(id);
    this.getComponent().postMessage({
        id:"MSG_CUSTOM_MOUSEOVERWIDGET",
        widget:oWidget
    });
}

/**
 * 鼠标移出部件
 */
Custom.prototype.mouseoutWidget = function(id) {
    var oWidget = this.getWidget(id);
    this.getComponent().postMessage({
        id:"MSG_CUSTOM_MOUSEOUTWIDGET",
        widget:oWidget
    });
}

/**
 * 获得组件
 * @param id
 */
Custom.prototype.getWidget = function(id) {
    for (var i = 0 ; i < this._widgets.length ; i++) {
        var comp = this._widgets[i];
        if (comp.getID() == id) {
            return comp;
        }
    }
    return null;
}

/**
 * 获得组件索引
 * @param id
 */
Custom.prototype.getWidgetIndex = function(id) {
    for (var i = 0 ; i < this._widgets.length ; i++) {
        var comp = this._widgets[i];
        if (comp.getID() == id) {
            return i;
        }
    }
    return null;
}

/**
 * 获得组件数量
 */
Custom.prototype.getWidgets = function() {
    var comps = [];
    for (var i = 0 ; i < this._widgets.length ; i++) {
        comps.push(this._widgets[i]);
    }
    comps.sort(function(comp1, comp2){
        return parseInt(comp1.getLayoutData().num) - parseInt(comp2.getLayoutData().num);
    });
    return comps;
}

Custom.prototype.getWidgetsLength = function() {
    return this.getWidgets().length;
}

/**
 * 创建组件等待图标
 */
Custom.prototype.createLoad = function(sName) {
    return $(
        "<div class='widget-load-item'>" +
            "<span class='widget-load-item-text'>" + sName + "</span>" +
        "</div>"
    );
}

/**
 * 开始加载组件
 */
Custom.prototype.startLoadWidget = function() {
    var that = this;
    this._tt = setInterval(function(){
        var oComp = that._waitLoad.shift();
        if (oComp) {
            try {
                oComp.load();
            } catch(e) {
                console.error(e);
            }
            $(".widget-load-item", oComp.getHTML()).remove();
        } else {
            clearInterval(that._tt);
        }
    }, 300);
}

Custom.prototype.getValue = function() {
    if (!this._hasLoad) {
        this.load();
    }
    var widgets = [];
    for (var i = 0 ; i < this._widgets.length ; i++) {
        var layoutData = this._widgets[i].getLayoutData()
        widgets.push({
            id:Math.uuid(), oid:layoutData.id, col:0, row:0, cmpid:layoutData.cmpid, url:layoutData.url, size_x:0, size_y:0,
            max_width:0, max_height:0, min_width:0, min_height:0,num:layoutData.num,
            container:this.getID(),widgetParam:{param:this._widgets[i].getParam(),chandler:this._widgets[i].getExCHandler()}
        });
    }
    return widgets;
}